<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-02
 * Time: 14:38
 */

namespace app\applet\controller;


use app\applet\BaseController;
use think\facade\Db;

class UserCreditController extends BaseController
{
    /**
     * 向组织捐献积分
     * @return \think\response\Json
     */
    /**
     * 向组织捐献积分
     * @return \think\response\Json
     */
    public function donateAction()
    {
        Db::startTrans();
        try {
            $organizationId = $this->post['organizationId'];

            $credit = $this->post['credit'];

            //1. 检查捐献积分是否合理
            $this->app->userCreditService->checkDonateCredit($this->user, $credit, $organizationId);

            //2. 查询组织是否存在
            $organization = $this->app->organizationService->getDetail($organizationId);

            $time = date('Y-m-d H:i:s');
            if ($organization->startedAt > $time || $organization->endAt < $time) {
                throw new \Exception('本组织已过助力期', 500);
            }

            //3. 捐献积分
            $this->app->userCreditService->donate($organization, $this->user, $credit);

            Db::commit();

            return json(['code' => 200, 'msg' => '捐献成功', 'data'=> []]);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }
}